import Vue from 'vue'

// 全局数据响应成功状态码 200
Vue.prototype.ResCode = 200

// 全局导出的http地址
Vue.prototype.EXPORTURL = 'http://192.168.2.111:9091'

// 一些工具方法
Vue.prototype.$utils = {
  // 转换时间戳
  parseTime: function(time, cFormat) {
    if (arguments.length === 0) {
      return null
    }
    const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
    let date
    if (typeof time === 'object') {
      date = time
    } else {
      if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
        time = parseInt(time)
      }
      if (typeof time === 'number' && time.toString().length === 10) {
        time = time * 1000
      }
      date = new Date(time)
    }
    const formatObj = {
      y: date.getFullYear(),
      m: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      i: date.getMinutes(),
      s: date.getSeconds(),
      a: date.getDay(),
    }
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
      let value = formatObj[key]
      // Note: getDay() returns 0 on Sunday
      if (key === 'a') {
        return ['日', '一', '二', '三', '四', '五', '六'][value]
      }
      if (result.length > 0 && value < 10) {
        value = '0' + value
      }
      return value || 0
    })
    return time_str
  },
  // 获取星期
  getDay(e) {
    switch (e) {
      case 1:
        return '星期一'
        break
      case 2:
        return '星期二'
        break
      case 3:
        return '星期三'
        break
      case 4:
        return '星期四'
        break
      case 5:
        return '星期五'
        break
      case 6:
        return '星期六'
        break
      case 0:
        return '星期日'
        break
      default:
        break
    }
  },
  // 此系统处理 maskForm 的公共方法
  maskForm: function(form, form1, value) {
    let startDateTime, endDateTime, startDate, endDate, startTime, endTime
    return new Promise((a, b) => {
      if (arguments.length == 1) {
        // 方便保存接口提交
        let c = {}
        form.forEach((n1, i1) => {
          n1.name == 'a' && (startDateTime = n1.value)
          n1.name == 'b' && (endDateTime = n1.value)
          n1.name == 'startDay' && (startDate = n1.value)
          n1.name == 'endDay' && (endDate = n1.value)
          n1.name == 'startTime' && (startTime = n1.value)
          n1.name == 'endTime' && (endTime = n1.value)
          !n1.value &&
            n1.required &&
            !n1.hidden &&
            b(n1.title + '(' + n1.name + ')' + ' 为必填字段')
          !n1.hidden && (c[n1.name] = n1.value)
        })
        if (
          startDateTime &&
          endDateTime &&
          new Date(endDateTime) - new Date(startDateTime) <= 0
        ) {
          return b('开始日期大于结束日期')
        }
        if (
          startDate &&
          endDate &&
          new Date(endDate) - new Date(startDate) <= 0
        ) {
          return b('开始日期大于结束日期')
        }
        if (
          startTime &&
          endTime &&
          new Date(endTime) - new Date(startTime) <= 0
        ) {
          return b('开始时间大于结束时间')
        }
        return a(c)
      } else if (arguments.length == 2) {
        // 方便编辑数据回写
        let d = JSON.parse(JSON.stringify(form1))
        d.forEach((n1, i1) => {
          if (n1.name in form) {
            n1.value = form[n1.name]
          }
        })
        a(d)
      }
    })
  },
  // 清空 maskForm 表单
  clearForm(form) {
    form.forEach((n1, i1) => {
      n1.value = ''
    })
  },
  /**
   * 计算请假时长
   * @param {Object} beginTime    开始时间
   * @param {Object} endTime      结束时间
   * @param {Object} stWorkTime   上班时间
   * @param {Object} enWrokTime   下班时间
   * @param {Object} isFreeTime  是否要去除午休工作时长
   * @param {Object} freeTimeMon  午休开始时间
   * @param {Object} freeTimeAft  午休结束时间
   *
   */
  getTotal(
    beginTime,
    endTime,
    stWorkTime,
    enWrokTime,
    isFreeTime,
    freeTimeMon,
    freeTimeAft,
  ) {
    var days
    var hours
    var date
    var freeTime = freeTimeAft - freeTimeMon
    var daysBetween
    var hour

    beginTime = beginTime.replace(/-/g, '/')
    var beginArr = beginTime.split(' ')
    var beginMonth = parseInt(beginArr[0].split('/')[1])
    var beginDay = parseInt(beginArr[0].split('/')[2])
    var beginHours = parseInt(beginArr[1].split(':')[0])
    var beginMin = parseInt(beginArr[1].split(':')[1])
    var beginHoursMin = beginHours + beginMin / 60

    endTime = endTime.replace(/-/g, '/')
    var endArr = endTime.split(' ')
    var endMonth = parseInt(endArr[0].split('/')[1])
    var endDay = parseInt(endArr[0].split('/')[2])
    var endHours = parseInt(endArr[1].split(':')[0])
    var endMin = parseInt(endArr[1].split(':')[1])
    var endHoursMin = endHours + endMin / 60

    //如果beginHoursMin时间小于上班时间都算上班时间
    if (beginHoursMin <= stWorkTime) {
      beginHoursMin = stWorkTime
    }
    //如果endHoursMin时间大于上班时间都算下班时间
    if (endHoursMin >= enWrokTime) {
      endHoursMin = enWrokTime
    }
    //如果结束时间在freeTimeMon和freeTimeAft之间都算freeTimeMon
    if (isFreeTime == true) {
      if (endHoursMin >= freeTimeMon && endHoursMin <= freeTimeAft) {
        endHoursMin = freeTimeMon
      }
    }

    //获取结束时间-开始时间的天数
    daysBetween = this.daysBetween(beginTime, endTime)
    if (daysBetween.length > 0) {
      var daysBetweenLen = daysBetween.length
      //午休
      if (isFreeTime == true) {
        hour = enWrokTime - stWorkTime - freeTime
        if (daysBetweenLen == 1) {
          //同一天
          hours = endHoursMin - beginHoursMin - freeTime
        } else if (daysBetweenLen == 2) {
          //跨一天
          //第一天的时长
          hours = enWrokTime - beginHoursMin
          //是否有午休
          if (beginHoursMin <= freeTimeMon) hours = hours - freeTime
          //第二天的时长
          hours += endHoursMin - stWorkTime
          //是否有午休
          if (endHoursMin >= freeTimeAft) hours = hours - freeTime
        } else {
          //跨两天以上
          //第一天的时长
          hours = enWrokTime - beginHoursMin
          //是否有午休
          if (beginHoursMin <= freeTimeMon) hours = hours - freeTime
          //中间时长
          hours += (daysBetweenLen - 2) * hour
          //最后一天时长
          hours += endHoursMin - stWorkTime
          //是否有午休
          if (endHoursMin >= freeTimeAft) hours = hours - freeTime
        }
        days = Math.floor(hours / hour)
        hours = hours % hour
        date = {days: days, hours: hours}
      } else {
        //非午休
        hour = enWrokTime - stWorkTime
        if (daysBetweenLen == 1) {
          //同一天
          hours = endHoursMin - beginHoursMin
        } else if (daysBetweenLen == 2) {
          //跨一天
          hours = enWrokTime - beginHoursMin
          //第二天的时长
          hours += endHoursMin - stWorkTime
        } else {
          //跨两天以上
          //第一天的时长
          hours = enWrokTime - beginHoursMin
          //中间时长
          hours += (daysBetweenLen - 2) * hour
          //最后一天时长
          hours += endHoursMin - stWorkTime
        }
        days = Math.floor(hours / hour)
        hours = hours % hour
        date = {days: days, hours: hours}
      }
    }
    return date
  },
  /**
   * 根据两个日期，判断相差天数
   * @param sDate1 开始日期 如：2016-11-01
   * @param sDate2 结束日期 如：2016-11-02
   * @returns {number} 返回相差天数
   */
  daysBetween(sDate1, sDate2) {
    var arr = []
    sDate1 = sDate1.substring(0, 10)
    sDate2 = sDate2.substring(0, 10)
    var startTime = this.gDate(sDate1)
    var endTime = this.gDate(sDate2)
    while (endTime.getTime() - startTime.getTime() >= 0) {
      var year = startTime.getFullYear()
      var month =
        startTime.getMonth().toString().length == 1
          ? '0' + startTime.getMonth().toString()
          : startTime.getMonth()
      var day =
        startTime.getDate().toString().length == 1
          ? '0' + startTime.getDate()
          : startTime.getDate()
      arr.push(year + '/' + month + '/' + day)
      startTime.setDate(startTime.getDate() + 1)
    }
    return arr
  },

  gDate(datestr) {
    datestr = datestr.replace(/-/g, '/')
    var temp = datestr.split('/')
    var date = new Date(temp[0], temp[1], temp[2])
    return date
  },
  downBlob(res, name) {
    const data = res.data
    const url = window.URL.createObjectURL(
      new Blob([data], {
        type:
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      }),
    )
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', new Date().getTime() + '_' + name + '.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  },
}
